package net.siufung.security.api.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import net.sf.jsqlparser.expression.LongValue;

/**
 * 当前租户上下文
 * @author 陈建峰
 * @since 2022/2/9 11:10 下午
 */
public class TenantContextHolder {

    /**
     * 线程安全 ThreadLocal
     */
    private final TransmittableThreadLocal<LongValue> threadLocal;

    /**
     * 构造函数
     */
    private TenantContextHolder() {
        this.threadLocal = new TransmittableThreadLocal<>();
    }

    /**
     * 静态内部类单例模式
     */
    private static final TenantContextHolder INSTANCE = new TenantContextHolder();

    /**
     * 创建实例
     */
    public static TenantContextHolder getInstance() {
        return TenantContextHolder.INSTANCE;
    }

    /**
     * 当前租户ID放入
     */
    public void setTenantId(LongValue tenantId) {
        threadLocal.set(tenantId);
    }

    /**
     * 获取上下文中的信息
     */
    public LongValue getTenantId() {
        return threadLocal.get();
    }

    /**
     * 设置当前租户
     */
    public void setTenantId(Long tenantId) {
        this.setTenantId(new LongValue(tenantId));
    }

    /**
     * 清空上下文
     */
    public void clear() {
        threadLocal.remove();
    }

}
